package com.ld.task;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

public class UseAtomic {
    static AtomicInteger atomicInteger = new AtomicInteger(1);

    public static void main(String[] args) {
        for (int i = 0; i < 4; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    int atoInt = atomicInteger.addAndGet(2); //先增加再返回
                    System.out.println("Thread" + Thread.currentThread().getName() + ":atoInt=" + atoInt);
                    System.out.println("Thread" + Thread.currentThread().getName() + ":set:"+atomicInteger.compareAndSet(3,4));//先比较再设置，设置失败返回false
                }
            }).start();
        }
        User user = new User();
        user.setAge(1);
        user.setName("Andy");
        AtomicReference<User> userAtomicReference = new AtomicReference<>(user);
        User user2 = new User();
        user2.setAge(3);
        user2.setName("Hello");
        userAtomicReference.getAndSet(user2);//先获取再设置
        System.out.println(user.getAge());
        System.out.println(userAtomicReference.get().getAge());
        System.out.println(userAtomicReference.compareAndSet(user, user2));//先比较再设置，设置失败返回false

        user.setAge(4);
        System.out.println(userAtomicReference.get().getAge());

        userAtomicReference.get().setAge(4);
        System.out.println(user.getAge());
    }

    static class User {
        private String name;
        private int age;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }
    }
}
